package com.ebt.m.customer.db;

import android.content.Context;

import com.ebt.m.data.DatabaseManager;
import com.ebt.m.data.greendao.CustomerInteractionDao;
import com.ebt.m.data.greendao.DaoMaster;
import com.ebt.m.data.greendao.DaoSession;
import com.ebt.m.homepage.CustomerEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.greendao.query.Query;

import java.util.List;


public class InteractionUtil {
	private static InteractionUtil instance;
	private CustomerInteractionDao interActionDao;

	private InteractionUtil(Context context) {
		// DaoMaster.DevOpenHelper openHelper =
		// LuBoApplication.getInstance().getHelper();
		// SQLiteDatabase db = openHelper.getWritableDatabase();
		DatabaseManager dm = DatabaseManager.getInstance(context);
		DaoMaster master = new DaoMaster(dm.open());
		DaoSession session = master.newSession();
		interActionDao = session.getCustomerInteractionDao();
	}

	public static synchronized InteractionUtil getInstance(Context context) {
		if (instance == null) {
			instance = new InteractionUtil(context);
		}
		return instance;
	}

	public CustomerInteractionDao getTopicItemDao() {
		return interActionDao;
	}

	/**
	 * eg. Query query = userDao.queryBuilder().where(
	 * Properties.FirstName.eq("Joe"), Properties.YearOfBirth.eq(1970))
	 * .build(); 
	 * List joesOf1970 = query.list(); 
	 * 使用query对象，可以改变参数继续查询
	 * query.setParameter(0, "Maria"); 
	 * query.setParameter(1, 1977);
	 * 
	 * @param query
	 * @return List<CustomerInteraction>
	 */
	public List<CustomerInteraction> query(Query<CustomerInteraction> query) {
		return query.list();
	}

	/**
	 * 
	 * @param interaction
	 * @return the row ID of the newly inserted row, or 0 if an error occurred
	 */
	public void insert(CustomerInteraction interaction) {
		try {
			long rowId = interActionDao.insert(interaction);
			if (rowId != 0) {
				EventBus.getDefault().post(new CustomerEvent());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void update(CustomerInteraction interaction) {

		try {
			interActionDao.update(interaction);
			EventBus.getDefault().post(new CustomerEvent());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *insert interaction with no notification
	 * @param interaction
	 * @return the row ID of the newly inserted row, or 0 if an error occurred
	 */
	public void insertWithNoNotify(CustomerInteraction interaction) {
		try {
			long rowId = interActionDao.insert(interaction);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
